package com.agileai.portal.controller.mobile;

import java.util.List;

import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.Group;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.DispatchRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.auth.SecurityUserMobileManage;
import com.agileai.portal.extend.mobile.MobileHelper;
import com.agileai.util.StringUtil;
import com.agileai.weixin.model.Constans;
import com.agileai.weixin.tool.SecurityAuthHelper;

public class WxRedirectHandler extends BaseHandler{
	private static boolean InitedWxConfigs = false;
	static{
		if (!InitedWxConfigs){
			AppConfig appConfig = BeanFactory.instance().getAppConfig();
			String appId = appConfig.getConfig("WxConfig", "AppId");
			String appSecret = appConfig.getConfig("WxConfig", "AppSecret");
			String token = appConfig.getConfig("WxConfig", "Token");
			if (StringUtil.isNotNullNotEmpty(appId) && StringUtil.isNotNullNotEmpty(appSecret)
					&& StringUtil.isNotNullNotEmpty(token)){
				Constans.Configs.APPID = appId;
				Constans.Configs.APPSECRET = appSecret;
				Constans.Configs.TOKEN = token;
				InitedWxConfigs = true;				
			}
		}
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		try {
			String serviceURL = null;
			String serviceId = param.get("serviceId");
			User user = (User)this.getUser();
			if (user == null){
				String openId = this.getOpenId();
				if (StringUtil.isNotNullNotEmpty(openId)){
					log.info("weixin openId is " + openId);
					DataRow row = this.getUserRowByOpenId(openId);
					String userCode = null;
					if (row == null || row.isEmpty()){
						userCode = "guest";
						row = this.getUserRowByUserCode(userCode);
						
						if (row == null || row.isEmpty()){
							throw new Exception("guest user is not exists , please contact administrator !");
						}
						serviceURL = this.buildServiceURL("m9", serviceId);
					}else{
						userCode = row.getString("USER_CODE");
						if (this.isRegistryUser(userCode)){
							serviceURL = this.buildServiceURL("m9", serviceId);
						}else{
							serviceURL = this.buildServiceURL("m3", serviceId);
						}
					}
					
					this.getSessionAttributes().put(MobileHelper.WxFirstMenuCode,serviceId);
					
					AppConfig appConfig = this.getAppConfig();
					String comeFromKey = appConfig.getConfig("WxConfig", "ComeFromKey");
					this.getSessionAttributes().put("isWxRedirect","true");
					this.getSessionAttributes().put("comeFromKey",comeFromKey);
					this.getSessionAttributes().put("username",userCode);
					this.getSessionAttributes().put("password",row.getString("USER_PWD"));
					this.getSessionAttributes().put("service",serviceURL);
					String casRedirectURL = this.getHandlerURL("CASRemoteLogin"); 
					return new RedirectRenderer(casRedirectURL);
				}else{
					request.setAttribute("javax.servlet.error.message","openId is not exists,please contact administrator !");
					String errorURL = this.getHandlerURL("Error");
					return new DispatchRenderer(errorURL);
				}
			}else{
				String openId = this.getOpenId();
				if (StringUtil.isNotNullNotEmpty(openId)){
					log.info("weixin openId is " + openId);
					String userCode = user.getUserCode();
					if (isGuestUser(userCode) || isRegistryUser(user)){
						serviceURL = this.buildServiceURL("m9", serviceId);	
					}else{
						serviceURL = this.buildServiceURL("m3", serviceId);
					}
					return new RedirectRenderer(serviceURL);
				}else{
					request.setAttribute("javax.servlet.error.message","openId is not exists,please contact administrator !");
					String errorURL = this.getHandlerURL("Error");
					return new DispatchRenderer(errorURL);
				}
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
			request.setAttribute("javax.servlet.error.message",e.getLocalizedMessage());
			String errorURL = this.getHandlerURL("Error");
			return new DispatchRenderer(errorURL);
		}
	}
	
	private String getOpenId() throws Exception{
		String openId = (String)this.getSessionAttribute("openId");
		if (openId == null){
			String code = request.getParameter("code");
			if (StringUtil.isNotNullNotEmpty(code)){
				openId = SecurityAuthHelper.getOpenId(code);
		        this.getSessionAttributes().put("openId", openId);				
			}else{
				throw new Exception("weixin code is null !");
			}
		}
		return openId;
	}
	
	private boolean isRegistryUser(String userCode){
		boolean result = false;
		SecurityUserMobileManage securityUserMobileManage = this.lookupService(SecurityUserMobileManage.class);
		List<DataRow> records = securityUserMobileManage.retrieveRegistryUserByUserCode(userCode);
		for(int i=0;i<records.size();i++){
			DataRow dataRow = records.get(i);
			if("NewUsers".equals(dataRow.get("GRP_CODE"))){
				result = true;
				break;
			}
		}
		return result;
	}
	
	private boolean isRegistryUser(User user){
		boolean result = false;
		List<Group> groupList = user.getGroupList();
		for(int i=0;i<groupList.size();i++){
			Group groupRow = groupList.get(i);
			if("NewUsers".equals(groupRow.getGroupCode())){
				result = true;
				break;
			}
		}
		return result;
	}
	
	private boolean isGuestUser(String userCode){
		boolean result = false;
		if ("guest".equals(userCode)){
			result = true;
		}
		return result;
	}

	private String buildServiceURL(String menuBarCode,String serviceId) {
		String result = null;
		String serverName = this.dispatchServlet.getServletContext().getInitParameter("serverName");
		
		if ("home".equals(serviceId)){
			result = serverName + "/portal/request/"+menuBarCode+"/index.ptml#/tab/home";
		}
		else if ("bbs".equals(serviceId)){
			result = serverName + "/portal/request/"+menuBarCode+"/index.ptml#/tab/bbs";
		}
		else if ("km".equals(serviceId)){
			result = serverName + "/portal/request/"+menuBarCode+"/index.ptml#/tab/km";
		}
		return result;
	}
	
	private DataRow getUserRowByOpenId(String openId){
		DataRow result = null;
		SecurityUserMobileManage securityUserMobileManage = this.lookupService(SecurityUserMobileManage.class);
		result = securityUserMobileManage.retrieveUserInfoByOpenId(openId);
		return result;
	}

	private DataRow getUserRowByUserCode(String userCode){
		DataRow result = null;
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		result = authorizationConfig.retrieveUserRecord(userCode);
		return result;
	}	
}